import React from 'react';
import { Link } from 'react-router-dom';

import MUtil from 'util/mm.jsx';
import User from 'service/user-service.jsx';

const __mm = new MUtil();
const __user = new User();

class NavTop extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      username: __mm.getStorage('userInfo').username || ''
    }
  }

  // 这是退出登陆
  onLogout(){
    __user.logout().then(res => {
      __mm.removeStorage('userInfo');
      // 因为  NavTop 组件并不是由 route 渲染的，所以不会有 history 这个属性
      // this.props.history.push('/login')
      // 下面这个方法可以实现跳转，但是有个问题，跳转的时候是重新加载了整个页面
      window.location.href = '/login';
    }, errMsg => {
      __mm.errorTips(errMsg);
    })
  }

  render() {
    return (
      <div className="navbar navbar-default top-navbar">
        <div className="navbar-header">
          <Link className="navbar-brand" to="/"><b>Happy</b>MMall</Link>
        </div>

        <ul className="nav navbar-top-links navbar-right">
          <li className="dropdown">
            <a className="dropdown-toggle" href="javascript:;">
              <i className="fa fa-user fa-fw"></i>
              {/* 如果没有取到这个字段 */}
              {
                this.state.username
                ? <span>欢迎, {this.state.username}</span>
                : <span>欢迎您</span>
              }
              <i className="fa fa-caret-down"></i>
            </a>
            <ul className="dropdown-menu dropdown-user">
              <li>
                <a onClick={() => {this.onLogout()}}>
                  <i className="fa fa-sign-out fa-fw"></i>
                  <span>退出登陆</span>
                </a>
              </li>
            </ul>
            {/* /.dropdown-user */}
          </li>
        </ul>
      </div>
    );
  }
}

export default NavTop;